const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            dataForm: {
                Coords: '',
                Unit_Quantity: '',
                Layer_Quantity: '',
                Room_Quantity: ''
            },
            Grid: [],
            house_type: [],
            personal: [],
            relation: [],
            childDataForm1: [{}],
            natural_resources_management: [],
            cityValue: ['230000', '232700', '232723'],
            cityValue1: [],
            city: [],
            city1: [],
            village_collective: [],
            is: true,
            blue_plate_tags:[]
        };
    },
    mounted() {
        this.getCategory();
        this.getCity();
        if (this.action == 'Add') {
            this.changeCity(this.cityValue)
        }

    },
    watch: {
        'dataForm.Village_SerialNumber'(val) {
            if (this.action == 'Modify' && this.is) {
                this.is = false;
                let str = this.dataForm.Village_SerialNumber
                console.log(this.dataForm);
                if (str.substring(0, 6)) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/clientOperation/getDistrictTree`,
                        type: "GET",
                        data: {
                            DistrictCode: str.substring(0, 6)
                        },
                        success: (data) => {
                            this.city1 = data[0].children;
                            this.cityValue1 = [str.substring(0, 9), str];
                            this.cityValue = [str.substring(0, 2) + '0000', str.substring(0, 4) + '00', str.substring(0, 6)]
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json",
                    });
                }
            }
        },
    },
    computed: {
        RoomNumbers() {
            const { Unit_Quantity, Layer_Quantity, Room_Quantity } = this.dataForm;
            if (!isNaN(Unit_Quantity) && !isNaN(Layer_Quantity) && !isNaN(Room_Quantity)) {
                let arr = [];
                for (let i = 1; i <= Number(Unit_Quantity); i++) {
                    for (let j = 1; j <= Number(Layer_Quantity); j++) {
                        for (let z = 1; z <= Number(Room_Quantity); z++) {
                            arr.push({
                                Blue_Plate_SerialNumber: this.dataForm.Blue_Plate_SerialNumber,
                                Unit_Number: i,
                                Layer_Number: j,
                                Room_Number: z,
                                Room_SerialNumber: i + '-' + (j < 10 ? '0' + j : j) + (z < 10 ? '0' + z : z),
                            })
                        }
                    }
                }
                return arr;
            }
            return []
        }
    },
    methods: {
        changeCity1(val) {
            if (val.length > 0) {
                this.dataForm.Village_SerialNumber = val[1];
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/generalBusiness/generalQueryByTableName`,
                    type: "POST",
                    data: {
                        Data: 'base_system_village_collective',
                        Condition: "VillageNumber = '" + val[1] + "'",
                    },
                    success: (data) => {

                        this.village_collective = data; // 直接使用 this
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            } else {
                this.dataForm.Village_SerialNumber = '';
            }

        },
        changeCity(val) {
            if (val.length > 0) {
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/clientOperation/getDistrictTree`,
                    type: "GET",
                    data: {
                        DistrictCode: val[2]
                    },
                    success: (data) => {
                        this.city1 = data[0].children;
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            }
        },
        getCity() {
            $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                    data.forEach(item => {
                        item.children.forEach(ite => {
                            ite.children.forEach(it => {
                                it.children = undefined
                            })
                        })
                    })
                    this.city = data;
                }
            });
        },
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'grid_information',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.Grid = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'natural_resources_management',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.natural_resources_management = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'personal_information',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.personal = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'blue_plate_house_type',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.house_type = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'relation_type',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.relation = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'blue_plate_tags',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.blue_plate_tags = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        let lJSONObject_ChildData_Options = new Object();
                        lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                        let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                        let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                        // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                        if (this[ls_DataForm][ls_primary_key]) {
                            this[ls_ChildDataForm].forEach(item => {
                                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                            })
                        }
                        //建立子表结构体
                        let JSONArray_ChildRecord = new Array();
                        JSONArray_ChildRecord = this[ls_ChildDataForm];
                        if (!this[ls_DataForm].Children) {
                            this[ls_DataForm].Children = new Object();
                        }
                        this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                    })
                } catch (error) {

                }
                // if (this.RoomNumbers.length > 0) {
                //     if (!this[ls_DataForm].Children) {
                //         this[ls_DataForm].Children = new Object();
                //     }
                //     this[ls_DataForm].Children['blue_plate_house_room'] = this.RoomNumbers;
                // }
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(this[ls_DataForm]);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(this[ls_DataForm]);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    let lJSONObject_Table_Add = new Object();
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    if (this.dataForm.Responsible_Person != this.dataForm.Responsible_Person_Original) {
                        let blue_plate_house_unit = [{
                            Blue_Plate_SerialNumber:this.dataForm.Blue_Plate_SerialNumber,
                            Blue_Plate_Personal_SerialNumber:this.dataForm.Responsible_Person,
                            Personal_SerialNumber:this.dataForm.Responsible_Person_Original
                        }];
                        lJSONObject_Table_Add['grid_blue_plate_log'] = blue_plate_house_unit;
                    }
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;
                    }
                    lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                if (!lJSONObject_DataSet['Add']) {
                    lJSONObject_DataSet['Add'] = new Object();
                }
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSave",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet,(res)=>{
                    if (res.Status == 'success') {
                        window.location.href = './index.html'
                        // window.history.go(-1);
                    }
                })
                // $.ajax({
                //     headers: requestHeaders(),
                //     url: `${mh}/generalBusiness/generalSave`,
                //     method: "post",
                //     data: {
                //         Data: JSON.stringify(lJSONObject_DataSet),
                //     },
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.location.href = './index.html'
                //             // window.history.go(-1);
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         requestPretreatment(XMLHttpRequest);
                //     },
                // });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
